import tkinter as tk
import random

def move_ball():
    # Get the current position of the ball
    x = canvas.coords(ball)[0]
    y = canvas.coords(ball)[1]

    # Generate random values for the new position
    dx = random.randint(-5, 5)
    dy = random.randint(-5, 5)

    # Update the position of the ball
    canvas.move(ball, dx, dy)

    # Check if the ball has reached the boundary of the canvas
    if x < 0 or x > canvas_width:
        dx = random.randint(-5, 5)
    if y < 0 or y > canvas_height:
        dy = random.randint(-5, 5)

    # Set the new velocity of the ball
    ball_dx = dx
    ball_dy = dy

    # Schedule the next move
    canvas.after(50, move_ball)

    
def create_ball():
        global ball, ball_dx, ball_dy

        # Create a ball at the center of the canvas
        ball = canvas.create_oval(canvas_width // 2 - 10, canvas_height // 2 - 10, canvas_width // 2 + 10, canvas_height // 2 + 10, fill="red")

        # Set the initial velocity of the ball
        ball_dx = 0
        ball_dy = 0

        # Start moving the ball
        move_ball()
def main():
    global canvas, canvas_width, canvas_height

    # Create the main window
    window = tk.Tk()
    window.title("Random Running Ball")

    # Set the size of the canvas
    canvas_width = 400
    canvas_height = 400

    # Create the canvas
    canvas = tk.Canvas(window, width=canvas_width, height=canvas_height, bg="white")
    canvas.pack()

    # Create the ball
    create_ball()

    # Start the main loop
    window.mainloop()
    
if __name__ == "__main__":
    main()



